package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.AuthorityDao;
import mil.af.amc.adpetracker.model.Authority;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.NonUniqueResultException;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * Hibernate DAO Implementation for Authority objects.
 *
 * Most methods that would normally modify an object are overriden to prevent the three basic roles from being altered
 *
 * @author TSgt Jason Ferguson
 */
@Repository("authorityDao")
public class HibernateAuthorityDao extends HibernateGenericDao<Authority> implements AuthorityDao {

    private static final Log log = LogFactory.getLog(Authority.class);

    public HibernateAuthorityDao() {
        super(Authority.class);
    }

    @Override
    public void delete(Authority persistentObject) {

    }

    @Override
    public void saveOrUpdate(Authority object) {

    }

    @Override
    public Authority save(Authority object) {
        throw new UnsupportedOperationException();
    }

//    public Integer add(Authority object) {
//
//        return null;
//    }

    @Override
    public Authority merge(Authority object) {

        return null;
    }

    @SuppressWarnings({"unchecked"})
    public Authority getByName(String name) {

        Criteria authorityCriteria = sessionFactory.getCurrentSession().createCriteria(Authority.class);
        authorityCriteria.add(Restrictions.ilike("authority", name));

        Authority result = null;
        try {
            result = (Authority) authorityCriteria.uniqueResult();
        } catch (NonUniqueResultException ex) {
            log.debug("getByName() threw NonUniqueResultException", ex);
            return null;
        } catch (HibernateException ex) {
            log.debug("getByName() threw HibernateException", ex);
        }

        return result;
//        DetachedCriteria crit = DetachedCriteria.forClass(Authority.class);
//        crit.add(Restrictions.ilike("authority", name));
//        List<Authority> results = (List<Authority>) getHibernateTemplate().findByCriteria(crit);
//
//        if (results.size() == 0) {
//            return null;
//        }
//
//        return results.get(0);
    }
}
